<?php

class Result
{
	private $oResult;
	
	public function __construct($res)
	{
		$this->oResult = $res;
	}
	
	public function __destruct()
	{
		if (is_object($this->oResult))
			mysql_free_result($this->oResult);
	}
	
	public function fetch()
	{
		return mysql_fetch_assoc($this->oResult);		
	}
	
	public function rows()
	{
		return mysql_num_rows($this->oResult);
	}
	
	public function begin()
	{
		mysql_data_seek($this->oResult, 0);
	}
	
	public function isOk()
	{
		if (is_object($this->oResult) || $this->oResult === true)
			return true;
		return false;
	}
}

class DataBase
{
	private static $sInstance;
	private $oConnect;	
	
	private function __construct()
	{
		$this->oConnect = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
		if ($this->oConnect === false) 
			die("ERROR: Fail to conect to data server!<br>");
		if (mysql_select_db(DB_BASE_NAME, $this->oConnect) === false) 
			die("ERROR: Fail to select " . DB_BASE_NAME . " database!<br>");
		mysql_set_charset("utf8", $this->oConnect);
	}
	
	public function __destruct() 
	{
		if (is_object($this->oConnect))
			mysql_close($this->oConnect);
	}

	public static function &i()
	{
		if (is_null(self::$sInstance) || !is_object(self::$sInstance))
			self::$sInstance = new self();
		
		return self::$sInstance;
	}
	
	public function query($query)
	{
		$res = mysql_query($query, $this->oConnect);
		if (DEBUG_MODE && $res === false)
		{
			var_dump($query);
			die($this->error());
		}
		return new Result($res);
	}
	
	public function error()
	{
		return mysql_error($this->oConnect);
	}
	
	public function hasError()
	{
		$err = mysql_error($this->oConnect);;
		return !empty($err);
	}
	
	public function insertId()
	{
		return mysql_insert_id($this->oConnect);
	}
	
	public function escape($str)
	{
		return mysql_real_escape_string($str, $this->oConnect);
	}
}

?>